<template>
  <div class="w-full">
    <div class="mb-4">
      <nav class="flex space-x-1 bg-background-800 p-1 rounded-lg" aria-label="Tabs">
        <UiButton
          v-for="tab in tabs"
          :key="tab.id"
          @click="activeTab = tab.id"
          variant="ghost"
          size="sm"
          :class="[
            'flex items-center px-4 py-2.5 rounded-md text-sm font-medium transition-colors duration-200 relative',
            activeTab === tab.id
              ? '!bg-background-700 !text-text-primary'
              : 'text-text-muted hover:text-text-secondary hover:bg-background-700'
          ]"
        >
          {{ tab.label }}
          <span 
            v-if="tab.count !== undefined" 
            :class="[
              'ml-2 px-2 py-0.5 text-xs rounded-full font-medium',
              activeTab === tab.id
                ? 'bg-background-600 !text-text-primary'
                : 'bg-background-600 text-text-muted'
            ]"
          >
            {{ tab.count }}
          </span>
        </UiButton>
      </nav>
    </div>

    <div class="mt-6">
      <div v-for="tab in tabs" :key="tab.id" v-show="activeTab === tab.id" class="animate-fade-in">
        <slot :name="tab.id" :tab="tab">
          {{ tab.content }}
        </slot>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { UiButton } from './index'

export interface Tab {
  id: string
  label: string
  count?: number
  content?: string
}

interface Props {
  tabs: Tab[]
  defaultTab?: string
  modelValue?: string
}

const props = withDefaults(defineProps<Props>(), {
  defaultTab: undefined,
  modelValue: undefined
})

const emit = defineEmits<{
  'update:modelValue': [value: string]
}>()

const internalActive = ref(props.modelValue || props.defaultTab || props.tabs[0]?.id || '')

// 同步外部 v-model 变化
watch(() => props.modelValue, (val) => {
  if (val && val !== internalActive.value) internalActive.value = val
})

// 当tabs变化时，确保active有效
watch(() => props.tabs, (newTabs) => {
  if (newTabs.length > 0 && !newTabs.find(tab => tab.id === internalActive.value)) {
    const next = props.modelValue || props.defaultTab || newTabs[0].id
    internalActive.value = next
    emit('update:modelValue', next)
  }
}, { immediate: true })

// 点击切换时，同步 v-model
watch(internalActive, (val) => {
  if (props.modelValue !== val) emit('update:modelValue', val)
})

// 暴露当前活动标签
defineExpose({
  activeTab: internalActive
})

// 对模板暴露引用名
const activeTab = internalActive
</script>